<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Cms\Service;

use Admin\Data\Common;
use Admin\Data\Config;
use Cms\Entity\SingleCms;
use Doctrine\ORM\EntityManager;

class SingleCmsManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加单页文章
     * @param array $data
     * @return SingleCms
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addSingleCms(array $data)
    {
        $singleCms = new SingleCms();
        $singleCms->valuesSet($data);

        $this->entityManager->persist($singleCms);
        $this->entityManager->flush();

        return $singleCms;
    }

    /**
     * 编辑单页文章
     * @param array $data
     * @param SingleCms $singleCms
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editSingleCms(array $data, SingleCms $singleCms)
    {
        $singleCms->valuesSet($data);
        $this->entityManager->flush();

        return true;
    }

    /**
     * 删除单页文章
     * @param SingleCms $singleCms
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteSingleCms(SingleCms $singleCms)
    {
        $imageList = Common::bodyImageArray($singleCms->getSingleCmsBody());

        $this->entityManager->remove($singleCms);
        $this->entityManager->flush();

        if ($imageList) foreach ($imageList as $imageValue) {
            if (stripos($imageValue, 'http') !== false) continue;
            @unlink(Config::CMS_IMAGE_PATH . basename($imageValue));
        }

        return true;
    }
}